//index.js
//获取应用实例
var util = require('../../utils/util.js');
var app = getApp()
var url = app.url
Page({
  data: {
    list: [],
    pid: "id",
    topImages: [],
    banners: [],
    navigates: [],
    indexRecommends: [],
    goodsRecommend: [],
    shopInfo: {},
    bgColor: {
      'roseRed': '#FF2955', 'lightBlue': '#73d3ff', 'orange': '#ff7200', 'pink': '#ff7383', 'green': '#5ccc87',
      'yellow': '#ffcd00', 'blue': '#007BFF', 'violet': '#ab73ff', 'brown': '#b39350', 'red': '#FF4444'},
    imageUrl: app.imageUrl,
    linkArr: {"goods": "../goods/", "goodDetail": "../goods/", "coupon": "../coupon/", "store": "../stores/" },
    isSetUserInfo: false,
    // 规格弹出层
    showLoadIngGg: true,
    isTrueGroup: false, // 是否开团
    goods: '', // 产品
    ggList: '', // 产品规格集合
    ggListArr: '', // 筛选规格
    ggValue0: '',
    ggValue1: '',
    ggValue2: '',
    isChoice: false,
    vaArr: [],
    goodsGg: {}, // 选中规格
    chPrice: '',
    onePrice: '', // 单价
    chStock: '',
    goodNum: '1',
    ddPrice: 0,
    ptPrice: 0,
    margin: 3,
    width: 168,
    loading: true,
    canIUse: true
  },
  onShareAppMessage: function (res) {
    return {
      title: ' ',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onPullDownRefresh: function () {
    this.initConfig()
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onShow: function () {

  },
  onLoad: function () {
    wx.showLoading({
      title: '加载中',
    })
    try {
      var res = wx.getSystemInfoSync()
      var w = res.windowWidth-12;
      var margin = parseInt(w * 0.01)
      var width = (w - margin * 4) / 2
      this.setData({ margin: margin, width: width })
    } catch (e) {}
    this.initConfig()
  },
  initConfig: function () {
    var that = this
    that.getUserInfo()
    that.initShopConfig()
  },
  getUserInfo: function () {
    var that = this
    wx.getUserInfo({
      lang: 'zh_CN',
      success: function (res) {
        app.userInfo = res.userInfo
        that.doLogin(res.userInfo, res.encryptedData, res.iv)
      },
      fail: function (res) {
        wx.showModal({
          title: '需要您授权才能正常显示',
          content: '请点击“去授权”并点击授权按钮，即可正常使用',
          confirmText: '去授权',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // wx.openSetting({
              //   success: function (re) {
              //     if (!re.authSetting["scope.userInfo"] || !re.authSetting["scope.userLocation"]) {
              //       var isset = that.data.isSetUserInfo
              //       if(!isset){
              //         that.getUserInfo()
              //       }
              //     }else{
              //       that.setData({ isSetUserInfo : true})
              //     }
              //   }
              // })
              console.log("用户点击确定")
              wx.navigateTo({
                url: '../authorize/authorize',
              })
            }
          }
        })
      }
    })
  },
  doLogin: function (userInfo, encryptedData, iv) {
    var that = this
    wx.login({
      success: function (res) {
        var params = { code: res.code, userInfo: userInfo, encryptedData: encryptedData, iv: iv }
        var encodingStr = app.ecbEncrypto(params)
        wx.request({
          url: app.url + '/web/member/recordTimes.htm',
          data: encodingStr,
          method: 'POST',
          success: function (res) {
            var decodingStr = app.ecbDecrypto(res.data)
            var rest = JSON.parse(decodingStr)
            console.log(rest)
            if (rest.isSuccess == 0) {
              app.memberId = rest.menberId
            }
          }
        })
      }
    })
  },
  initShopConfig: function () {
    var that = this
    var params = {}
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/shopCache.do',
      data: encodingStr,
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          if (!rest.shopConfig ) {
            console.log("shopConfig加载失败")
            wx.showLoading({
              title: '数据加载失败',
            })
            return
          } else {
            if (rest.shopConfig) {
              var shopConfig = rest.shopConfig
              app.shopConfig = shopConfig
              that.constructShopSettings(shopConfig)
              that.setData({
                shopConfig: shopConfig, banners: shopConfig.lunbo, indexRecommends: shopConfig.indexRecommend,
                goodsRecommend: shopConfig.goodsRecommend, navigates: shopConfig.navigate, loading: false});
            }
            if (rest.shopGoodsGroup) {
              app.goodTypes = rest.shopGoodsGroup
            }
            wx.hideLoading()
          }
        }else {
          console.log("请求接口异常")
          wx.showLoading({
            title: '数据加载失败',
          })
        }
      },
      fail: function (res) {
        console.log(res)
        wx.showLoading({
          title: '请求失败',
        })
      },
      complete: function () {
        wx.stopPullDownRefresh()
      }
    })
  },

  constructShopSettings: function (shopConfig) {
    var that = this
    if (shopConfig) {
      //设置轮播
      try {
        var banners = JSON.parse(shopConfig.lunbo)
        shopConfig.lunbo = banners
      } catch (e) {
        shopConfig.lunbo = {}
      }
      //设置首页导航
      try {
        var navigates = JSON.parse(shopConfig.navigate)
        shopConfig.navigate = navigates
      } catch (e) {
        shopConfig.navigate = {}
      }
      //设置产品推荐
      try {
        var goodsRecommend = JSON.parse(shopConfig.goodsRecommend)
        for (var i = 0; i < goodsRecommend.length; i++) {
          var result = goodsRecommend[i].goods
          for (var n = 0; n < result.length; n++) {
            if (result[n].isGroup) {
              var groupStartTime = result[n].groupStartTime
              var leftTime = new Date() - new Date(groupStartTime); //计算剩余的毫秒数 
              goodsRecommend[i].goods[n].isBegin = leftTime >= 0
            } else {
              var saleTime = result[n].saleTime
              var leftTime = new Date() - new Date(saleTime); //计算剩余的毫秒数 
              if (leftTime < 0) {
                goodsRecommend[i].goods.splice(n)
              } else {
                if (result[n].goodsName.length > 25) {
                  goodsRecommend[i].goods[n].goodsName = goodsRecommend[i].goods[n].goodsName.substr(0, 25) + "..."
                }
              }
            }
          }
        }
        shopConfig.goodsRecommend = goodsRecommend
      } catch (e) {
        shopConfig.goodsRecommend = {}
      }
      //设置首页推荐
      try {
        var indexRecommends = JSON.parse(shopConfig.indexRecommend)
        shopConfig.indexRecommend = indexRecommends
      } catch (e) {
        shopConfig.indexRecommend = {}
      }
    }
  },
  bindGoodRecommend: function (event) {
    var linkArr = {
      "goods": "../goods/goodsList", "goodsDetail": "../goods/goodDetail?id=", "about": "../about/about",
      "helpCenter": "../helpCenter/helpCenter", "goodTypes": "../goods/goodsList?" }
    var that = this
    var obj = event.currentTarget.dataset.obj
    if (obj.linkType != "none") {
      var url = linkArr[obj.linkType]
      if (obj.linkType == "goodTypes") url = url + obj.linkUrl
      if (obj.linkType == "goodsDetail") {
        var id = obj.linkUrl.substr(obj.linkUrl.indexOf("=") + 1)
        url = url + id
      } 
      wx.navigateTo({
        url: url
      })
    }
  },
  bindtoDetail: function (event) {
    var id = event.currentTarget.dataset.gid
    wx.navigateTo({
      url: "../goods/goodDetail?id=" + id
    })
  }
})
